// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({env: cloud.DYNAMIC_CURRENT_ENV})
// developer为开发版；trial为体验版； formal 为正式版；默认为正式版
let miniprogramState ="formal";
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  let { todoid, avatarUrl, nickName } = event;
  let user = {
    openid,
    avatarUrl,
    nickName,
    creatTime: new Date(),
  }
  const db = cloud.database();
  let userInfo = await db.collection('todos').doc(todoid).get();
  userInfo = userInfo ? userInfo.data : null;
  let acceptResult =null;
  if (userInfo && userInfo.openid != openid) {
    let invite = userInfo.invite;
    let findUser = invite ? invite.find(item => item.openid == openid) : null;
    if (!findUser) {
      const _ = db.command;
       acceptResult = await db.collection('todos').doc(todoid).update({
        data: {
          invite: _.push([user]),
          inviteCount: _.inc(1)
        }
      })
    }
    let data1 ={
      touser: openid,
      page: 'pages/list/detial?todoid=' + todoid,
      lang: 'zh_CN',
      data: {
        name1: {
          value:  userInfo.nickName?String(userInfo.nickName).substring(0,10) :'无'
        },
        thing2:{
          value: userInfo.address.substring(0,20)||''
        },
        date3: {
          value: userInfo.date+' '+userInfo.time+":00"
        },
        thing7: {
          value: userInfo.markInfo.substring(0,20)||"暂无信息"
        },
        phrase9: {
          value: '成功'
        },
      },
      templateId: '9fP7SL46Ny9kanVRYrPiJxhqvB4j8tl31Hlc3TTC_4A',
      miniprogramState
    };
    try {

      // 发送 发送接受者
      const result1 = await cloud.openapi.subscribeMessage.send(data1)
      console.log('发送给约定接受者：'+ nickName,result1,JSON.stringify(data1));
      // 发送给 发起者
    } catch (error) {
      console.log('异常，发送给约定接受者：'+ nickName,error,JSON.stringify(data1))
    }
    let data2={
      touser: userInfo.openid,
      page: 'pages/list/detial?todoid=' + todoid,
      lang: 'zh_CN',
      data: {
        date1: {
          value: userInfo.date+' '+userInfo.time+":00"
        },
        phrase4:{
          value: '预约成功'
        },
        thing8: {
          value: nickName?String(nickName).substring(0,20):'无'
        },
        phrase5: {
          value: userInfo.markInfo.substring(0,5)||"暂无信息"
        },
      },
      templateId: 'Y0DtS_uctqpi9Bzwcu81YAY5AX-L6wQ6o3UtyQX-5u8',
      miniprogramState
    };
    try {
      const result2 = await cloud.openapi.subscribeMessage.send(data2)
      console.log('发送给约定发起者：'+ userInfo.nickName,result2,JSON.stringify(data2));
    } catch (error) {
      console.log('异常发送给约定发起者：'+ userInfo.nickName,error,JSON.stringify(data2))
    }
    return acceptResult;
  }

}